import { Component, OnInit, ViewChild } from '@angular/core';
import { DialogService } from 'app/shared/dialog';
import { NotificationService, ToolsService } from 'app/shared/service';
import { UserManagementService } from '../user-management.service';
import { AddRoleComponent } from './add-role/add-role.component';
import { PublicService } from 'app/public/public.service';
import * as moment from 'moment';
import { differenceInCalendarDays } from 'date-fns';

@Component({
    selector: 'itmp-manage-role',
    templateUrl: './manage-role.component.html',
    styleUrls: ['./manage-role.component.css']
})
export class ManageRoleComponent implements OnInit {
    @ViewChild(AddRoleComponent) private addRoleComponent: AddRoleComponent;
    isVisible = false; // 模态框隐藏
    isOkLoading = false;
    selectedUser = null; // 选中的每行tr数据
    addRoleTitle: string; // 模态框的title
    isVisibleMiddle = false;
    totalEle = 0;
    listOfData = []; // 列表数据的数组
    renderHeader = []; // 表头数据的数组
    searchData: any; // 搜索数据的对象
    selectionList: Array<{ label: string; value: string }> = [
        { label: 'Administrator', value: 'Administrator' },
        { label: 'Operator', value: 'Operator' },
        { label: 'Supervisor', value: 'Supervisor' }
    ];
    // 右上角的打印，放大，下载等图标
    toolbarList = [{ className: 'icon-dayinfuyin-' }];
    isDeleteLoading = false;
    // nzOkDisabled: string;
    queryName = null;
    queryDes = null;
    // 分页数据的对象
    pagination = {
        totalEle: 25, // 总条数
        currentPage: 1, // 当前页数
        currentSize: 10, // 当前页的条数
        pageSize: 10 // 设置当前页可以显示的条数
    };
    dateRange = [];
    dateUpRange = [];
    queryStartTime = null;
    queryEndTime = null;
    queryUpStartTime = null;
    queryUpEndTime = null;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    constructor(
        private dialog: DialogService,
        private message: NotificationService,
        private UMService: UserManagementService,
        private tools: ToolsService,
        private pub: PublicService
    ) {}

    ngOnInit() {
        this.renderHeader = [
            {
                name: 'RoleName',
                key: null,
                value: 'roleName',
                isChecked: true
            },
            {
                name: 'CreateDate',
                key: null,
                value: 'createDate',
                isChecked: true
            },
            {
                name: 'UpdateDate',
                key: null,
                value: 'updateDate',
                isChecked: true
            },
            {
                name: 'Description',
                key: null,
                value: 'descriptio',
                isChecked: true
            }
            // {
            //     name: 'No.ofUsersWithThisRole',
            //     key: null,
            //     value: 'No.ofUsersWithThisRoles',
            //     isChecked: true
            // }
        ];
        this.getData();
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('23', this.accessButton);
    }
    // 获取数据
    getData() {
        if (this.queryName === '' || this.queryDes === '') {
            this.queryName = null;
            this.queryDes = null;
        }
        const queryData = {
            pageSize: this.pagination.pageSize,
            pageNum: this.pagination.currentPage,
            condition: {
                userRole_Id: null,
                createTime: {
                    startTime: this.queryStartTime,
                    endTime: this.queryEndTime
                },
                updateTime: {
                    startTime: this.queryUpStartTime,
                    endTime: this.queryUpEndTime
                },
                roleName: this.queryName,
                description: this.queryDes
            }
        };
        // 获取manageRole数据
        this.UMService.getAllUserRole(queryData).subscribe(res => {
            if (res.errCode === '000000') {
                this.listOfData = res.content.content;
                this.pagination.currentPage = res.content.pageNum;
                this.pagination.currentSize = res.content.numberOfElements;
                this.pagination.totalEle = res.content.totolElements;
            }
        });
    }
    // 新建或则修改
    addOrEdit(flag) {
        if (flag === 'add') {
            this.addRoleTitle = 'Add_Role';
            // this.cancelActive();
            this.isVisible = true;
            this.selectedUser = {
                createTime: '',
                description: '',
                methodAccess: [],
                roleName: '',
                userRole_Id: 0
            };
            setTimeout(() => {
                if (this.addRoleComponent) {
                    this.addRoleComponent.getTreeList(this.selectedUser, flag);
                }
            });
        } else {
            this.addRoleTitle = 'Edit_Role';
            // this.nzOkDisabled = 'true';
            if (this.selectedUser && this.selectedUser.roleName) {
                this.isVisible = true;
                setTimeout(() => {
                    if (this.addRoleComponent) {
                        this.addRoleComponent.getTreeList(this.selectedUser, flag);
                    }
                });
            } else {
                // 提醒用户未选择要编辑的内容
                this.message.notify({ type: 'warning', path: 'UserManagement.ManageRole.select_notify' });
            }
        }
    }
    // 刷新
    refresh(): void {
        this.queryStartTime = this.getTimeStamp();
        this.queryEndTime = new Date().getTime();
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryName = null;
        this.queryDes = null;
        this.selectedUser = null;
        this.getData();
    }
    // 搜索
    onSearch(e): void {
        // 初始化当前页
        this.pagination.currentPage = 1;
        this.getData();
    }
    // 取消选中
    cancelActive(): void {
        this.selectedUser = {
            roleName: null
        };
        this.listOfData.forEach((data, index) => {
            data.active = false;
        });
    }
    // 点击tr取值
    click(i): void {
        this.addRoleTitle = 'Edit Role';
        this.listOfData.forEach((data, index) => {
            data.active = false;
            if (i === index) {
                // 点击每个tr给与样式active
                data.active = true;
                /* const obj = {
                    userRole_Id: data.userRole_Id,
                    roleName: data.roleName,
                    createtime: data.createtime,
                    description: data.description,
                    methodAccess
                }; */
                this.selectedUser = this.tools.isClone(data);
            }
        });
    }
    // 删除
    delete() {
        this.isDeleteLoading = false;
        if (this.selectedUser) {
            this.dialog
                .confirm({
                    title: 'UserManagement.ManageRole.Delete_Role',
                    content: 'UserManagement.ManageRole.Delete_Content',
                    buttonOkTxt: 'UserManagement.ManageRole.Delete_Save',
                    buttonCancelTxt: 'UserManagement.ManageRole.Delete_Cancel'
                })
                .subscribe(res => {
                    if (res) {
                        this.confirmDelete();
                    } else {
                        this.cancelDelete();
                    }
                });
        } else {
            // 提醒用户未选择要删除的内容
            this.message.notify({ type: 'warning', path: 'UserManagement.ManageRole.delete_notify' });
        }
    }
    // 获取access right树节点
    getTreeNodes(node) {}
    // 确认删除
    confirmDelete() {
        this.UMService.deleteUserRole(this.selectedUser).subscribe(
            res => {
                if (res.code === '900011') {
                    // organization正在使用
                    this.message.notify({ type: 'warning', path: 'UserManagement.ManageRole.fail_notify' });
                }
                this.refresh();
            },
            err => {}
        );
    }
    // 取消删除
    cancelDelete() {}

    getTimeStamp() {
        const nowdate = new Date();
        nowdate.setMonth(nowdate.getMonth() - 3);
        const y = nowdate.getFullYear();
        const m = nowdate.getMonth() + 1;
        const d = nowdate.getDate();
        const formatwdate = y + '-' + m + '-' + d;
        return new Date(formatwdate).getTime();
    }
    onChange(result: Date): void {
        this.queryStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }
    onUpdateChange(result: Date): void {
        this.queryUpStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryUpEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }
    // 日期选择确定
    onOk(result: Date): void {}
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        this.pagination.currentPage = 1;
        this.getData();
    }
    updateSuccess() {
        this.isVisible = false;
        this.selectedUser = null;
        this.refresh();
    }
    filterSearch() {
        this.pagination.currentPage = 1;
        this.pagination.currentSize = 10;
        this.getData();
    }
    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
